package gae.util.http.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Header {
    
    private Map<String, List<String>> headers = new HashMap<String, List<String>>();
    
    
    public void set(Map<String, List<String>> headers) {
        this.headers = headers;
    }
    
    public void set(String key, String value) {
        List<String> values = new ArrayList<String>();
        values.add(value);
        
        headers.put(key, values);
    }
    
    public void add(String key, String value) {
        List<String> header = headers.get(key);
        if (header == null) {
            List<String> values = new ArrayList<String>();
            values.add(value);
            headers.put(key, values);
        } else {
            header.add(value);
        }
    }
    
    public String toString() {
        StringBuilder sb = new StringBuilder("Header[");
        Iterator<String> ite = headers.keySet().iterator();
        while (ite.hasNext()) {
            String key = ite.next();
            sb.append(key);
            sb.append("=");
            sb.append(headers.get(key));
            if (ite.hasNext()) {
                sb.append(" ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
    
    public Set<String> keys() {
        return headers.keySet();
    }
    
    public List<String> get(String key) {
        List<String> result = headers.get(key);
        if (result == null) {
            result = headers.get(key.toLowerCase());
        }
        
        return result;
    }
    
    public Cookie getCookie() {
        Cookie cookie = new Cookie();
        List<String> setCookies = get("Set-Cookie");
        if (setCookies != null) {
            Iterator<String> ite = setCookies.iterator();
            while (ite.hasNext()) {
                cookie.addCookieFromHeaderValue(ite.next());
            }
        }
        return cookie;
    }
    
    public void setCookie(Cookie cookie) {
        List<String> list = cookie.getHeaders();
        if (list.size() > 0) {
            headers.put("Cookie", list);
        }
    }
    
}
